const api = require('../../utils/api.js');
const app = getApp();
const { gatherAction = '', reportAction = '' } = require('../../utils/utils');

let is_loading_more = false;
let is_no_more = false;

Page({
  data: {
    cat_id: '',
    page: 1,
    cat_list: [],
    goods_list: [],
    show_cart: '',
    sort: 0,
    sort_type: -1,
    theme: app.themeData,
    abnorData: {
      imgSrc: app.imgUrl + 'abnor-19.png',
      text: '暂无商品',
    },
    unit: '',
    show_attr_picker: false,
    form: {
      number: 1,
    },
    quickCat: true,
    useTabbar: !(app.tabbarindex === 0 && app.siteInfo.tabbar_type === '1'),
    toView: '',
    cat_style: 5,
    is_show_line: false,
    imgUrl: app.imgUrl,
  },

  onLoad(options) {
    let that = this;
    this.setData({
      orgPrice: app.ws_micro_shop_globalData.orgPrice,
      useTabbar: this.data.useTabbar && app.getTabBarStatus(),
    });
    let opts = options || {};
    app.v8_card_seller_actions_log = [];
    app.pageOnLoad(this);
    app.loadCurrencyUnit().then(res => {
      that.setData({
        unit: res.unit,
      });
    });
    this.setData({
      opts,
    });
    // opts.cat_name && wx.setNavigationBarTitle({
    //   title: decodeURIComponent(opts.cat_name),
    // })
    this.loadCatStyle();
    this.loadData(options);
  },

  onShow() {
    let _this = this;
    let list_page_reload = wx.getStorageSync('list_page_reload');
    if (list_page_reload) {
      let list_page_options = wx.getStorageSync('list_page_options');
      wx.removeStorageSync('list_page_options');
      wx.removeStorageSync('list_page_reload');
      let cat_id = Number(list_page_options.cat_id) || '';
      _this.setData({
        cat_id,
      });
      let cat_list = _this.data.cat_list;
      for (let i in cat_list) {
        if ({}.hasOwnProperty.call(cat_list, i)) {
          let in_list = false;
          for (let j in cat_list[i].list) {
            if (Number(cat_list[i].list[j].id) === cat_id) {
              cat_list[i].list[j].checked = true;
              in_list = true;
            } else {
              cat_list[i].list[j].checked = false;
            }
          }
          if (in_list || cat_id === Number(cat_list[i].id)) {
            cat_list[i].checked = true;
            if (cat_list[i].list && cat_list[i].list.length > 0) {
              _this.setData({
                height_bar: 'height-bar',
              });
            }
          } else {
            cat_list[i].checked = false;
          }
        }
      }
      _this.setData({
        cat_list,
      });
      _this.reloadGoodsList();
    }
  },

  onHide() {
    reportAction && reportAction();
  },

  onUnload() {
    reportAction && reportAction();
  },

  loadCatStyle() {
    let _this = this;
    app.ws_micro_shoprequest({
      url: api.default.catstyle,
      success: function(res) {
        if (res.code === 0) {
          _this.setData({
            cat_style: res.data.cat_style,
          });
        }
      },
    });
  },

  catItemClick(e) {
    let target = e.currentTarget.dataset;
    let list = this.data.cat_list2;
    for (let i = 0; i < list.length; i++) {
      if (Number(list[i].id) === Number(target.id)) {
        list[i].checked = true;
      } else {
        list[i].checked = false;
      }
    }
    this.setData({
      cat_id: target.id,
      toView: target.opt,
      cat_list2: list,
      is_show_line:false,
    });
    this.reloadGoodsList();
  },

  loadData(options) {
    let _this = this;
    let cat_list = wx.getStorageSync('cat_list');
    let height_bar = '';
    if (options.cat_id) {
      for (let i in cat_list) {
        if ({}.hasOwnProperty.call(cat_list, i)) {
          let in_list = false;
          if (Number(cat_list[i].id) === Number(options.cat_id)) {
            cat_list[i].checked = true;
            if (cat_list[i].list.length > 0) {
              height_bar = 'height-bar';
            }
          }
          for (let j in cat_list[i].list) {
            if (Number(cat_list[i].list[j].id) === Number(options.cat_id)) {
              cat_list[i].list[j].checked = true;
              in_list = true;
              height_bar = 'height-bar';
            }
          }
          if (in_list) {
            cat_list[i].checked = true;
          }
        }
      }
    }
    _this.setData({
      cat_list,
      cat_id: options.cat_id || '',
      toView: 'item' + options.cat_id,
      height_bar,
    });
    _this.reloadGoodsList();
  },

  catClick(e) {
    let _this = this;
    let cat_id = '';
    let index = Number(e.currentTarget.dataset.index);
    let cat_list = _this.data.cat_list;
    for (let i in cat_list) {
      if ({}.hasOwnProperty.call(cat_list, i)) {
        for (let j in cat_list[i].list) {
          if ({}.hasOwnProperty.call(cat_list[i].list, j)) {
            cat_list[i].list[j].checked = false;
          }
        }
        if (Number(i) === index) {
          cat_list[i].checked = true;
          cat_id = cat_list[i].id;
        } else {
          cat_list[i].checked = false;
        }
      }
    }
    let height_bar = '';
    if (cat_list[index].list.length > 0) {
      height_bar = 'height-bar';
    }
    _this.setData({
      cat_list,
      cat_id,
      height_bar,
    });
    _this.reloadGoodsList();
  },

  subCatClick(e) {
    let _this = this;
    let cat_id = '';
    let index = Number(e.currentTarget.dataset.index);
    let parent_index = Number(e.currentTarget.dataset.parentIndex);
    let cat_list = _this.data.cat_list;
    for (let i in cat_list) {
      if ({}.hasOwnProperty.call(cat_list, i)) {
        for (let j in cat_list[i].list) {
          if (Number(i) === parent_index && Number(j) === index) {
            cat_list[i].list[j].checked = true;
            cat_id = cat_list[i].list[j].id;
          } else {
            cat_list[i].list[j].checked = false;
          }
        }
      }
    }
    _this.setData({
      cat_list,
      cat_id,
    });
    _this.reloadGoodsList();
  },

  allClick() {
    let _this = this;
    let cat_list = _this.data.cat_list;
    for (let i in cat_list) {
      if ({}.hasOwnProperty.call(cat_list, i)) {
        for (let j in cat_list[i].list) {
          if ({}.hasOwnProperty.call(cat_list[i].list, j)) {
            cat_list[i].list[j].checked = false;
          }
        }
        cat_list[i].checked = false;
      }
    }
    _this.setData({
      cat_list,
      cat_id: '',
      height_bar: '',
    });
    _this.reloadGoodsList();
  },

  reloadGoodsList() {
    let _this = this;
    is_no_more = false;
    _this.setData({
      page: 1,
      goods_list: [],
      show_no_data_tip: false,
    });
    let cat_id = _this.data.cat_id || '';
    let p = _this.data.page || 1;
    let keyword = _this.data.keyword || '';
    wx.showLoading({
      title: '正在加载...',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url:
        String(cat_id) === 'vip'
          ? api.default.index_new
          : api.default.goods_list,
      data: {
        cat_id:
          String(cat_id) === 'vip'
            ? ''
            : this.data.opts.from === 'add-on'
              ? ''
              : cat_id,
        is_integral: _this.data.opts.integral,
        page: p,
        sort: _this.data.sort,
        sort_type: _this.data.sort_type,
        keyword: keyword || '',
        type: cat_id == 'vip' ? 'goods_list' : '',
      },
      success: function(res) {
        wx.hideLoading();
        if (res.code === 0) {
          if (res.data.list.length === 0) {
            is_no_more = true;
            _this.setData({
              is_show_line: p > 1 ? true : false,
            })
          }
          // res.data.list.forEach((item)=>{
          //   item.currency =  _this.data.unit;
          //   item.orgPrice = app.ws_micro_shop_globalData.orgPrice;
          // })
          _this.setData({
            page: p + 1,
            goods_list: res.data.list,
            show_cart: res.data.show_cart,
            cat_list2: res.data.cat_list
              ? res.data.cat_list.map((item, index) => {
                const data = Object.assign({}, item, {
                  checked: false,
                  name: item.name,
                  big_pic_url: item.big_pic_url,
                  id: item.id,
                  parent_id: item.parent_id,
                  pic_url: item.pic_url,
                  store_id: item.store_id,
                });
                if (item.id === _this.data.cat_id) {
                  data.checked = true;
                }
                return data;
              })
              : [],
          });
        }
        _this.setData({
          show_no_data_tip: _this.data.goods_list.length === 0,
        });
      },
    });
  },

  loadMoreGoodsList() {
    let _this = this;
    if (is_loading_more) {
      return;
    }
    _this.setData({
      show_loading_bar: true,
    });
    is_loading_more = true;
    let cat_id = _this.data.cat_id || '';
    let p = _this.data.page || 2;
    wx.showLoading({
      title: '加载更多...',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url:
        String(cat_id) === 'vip'
          ? api.default.index_new
          : api.default.goods_list,
      data: {
        cat_id:
          String(cat_id) === 'vip'
            ? ''
            : this.data.opts.from === 'add-on'
              ? ''
              : cat_id,
        is_integral: _this.data.opts.integral,
        page: p,
        sort: _this.data.sort,
        sort_type: _this.data.sort_type,
        type: String(cat_id) === 'vip' ? 'goods_list' : '',
      },
      success: function(res) {
        wx.hideLoading();
        if (res.data.list.length === 0) {
          is_no_more = true;
          // wx.showToast({
          //   title: '没有更多数据了',
          //   icon: 'none',
          //   duration: 2000,
          // });
          _this.setData({
            is_show_line: p > 1 ? true : false,
          })
        }
        let goods_list = _this.data.goods_list.concat(res.data.list);
        _this.setData({
          goods_list: goods_list,
          page: p + 1,
        });
      },
      complete: function() {
        is_loading_more = false;
        _this.setData({
          show_loading_bar: false,
        });
      },
    });
  },

  onReachBottom() {
    if (is_no_more) {
      return;
    }
    this.loadMoreGoodsList();
  },

  sortClick(e) {
    let _this = this;
    let sort = Number(e.currentTarget.dataset.sort);
    let default_sort_type = !e.currentTarget.dataset.default_sort_type
      ? -1
      : e.currentTarget.dataset.default_sort_type;
    let sort_type = _this.data.sort_type;
    if (Number(_this.data.sort) === sort) {
      if (Number(default_sort_type) === -1) {
        return;
      }
      if (Number(_this.data.sort_type) === -1) {
        sort_type = default_sort_type;
      } else {
        sort_type = Number(sort_type) === 0 ? 1 : 0;
      }
    } else {
      sort_type = default_sort_type;
    }
    _this.setData({
      sort,
      sort_type,
      is_show_line: false,
    });
    _this.reloadGoodsList();
  },

  collectFormId(e) {
    app.collectFormId(e);
  },

  selectDefaultAttr(use_attr, attr_group_list) {
    let _this = this;
    if (Number(use_attr) !== 0) {
      return;
    }
    for (let i in attr_group_list) {
      if (Object.prototype.hasOwnProperty.call(attr_group_list, i)) {
        for (let j in attr_group_list[i].attr_list) {
          if (Number(i) === 0 && Number(j) === 0) {
            attr_group_list[i].attr_list[j]['checked'] = true;
          }
        }
      }
    }
    _this.setData({
      attr_group_list,
    });
  },

  hideAttrPicker() {
    this.setData({
      show_attr_picker: false,
    });
  },
  disabledClick() {},

  showAttrModal(e) {
    let that = this;
    let id = e.currentTarget.dataset.gid;
    let member_only = e.currentTarget.dataset.member_only;
    let userInfo = wx.getStorageSync('user_info');
    if (Number(member_only) === 1 && userInfo && userInfo.level === -1) {
      wx.showModal({
        title: '提示',
        content: '您还不是会员,不能购买此商品',
        showCancel: false,
        success(res) {},
      });
      return false;
    }
    app.ws_micro_shoprequest({
      url: api.default.getattr,
      method: 'GET',
      data: {
        id,
      },
      success: function(res) {
        if (res.code === 0) {
          let resp = res.data;
          that.setData({
            goods: resp,
            attr_group_list: resp.attr_group_list,
            // goodsnum: resp.num,
            // goodsunit: resp.unit,
            // goodsprice: resp.price,
            // pic_list: resp.pic_list,
            show_attr_picker: true,
            member_only,
            id,
            'form.number': 1,
          });
          that.selectDefaultAttr(resp.use_attr, resp.attr_group_list);
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
          });
        }
      },
    });
    gatherAction && gatherAction('showAttrModal');
  },

  numberSub() {
    let num = this.data.form.number;
    if (num <= 1) {
      return true;
    }
    num--;
    this.setData({
      form: {
        number: num,
      },
    });
  },

  numberAdd() {
    let num = this.data.form.number;
    num++;
    this.setData({
      form: {
        number: num,
      },
    });
  },

  numberBlur(e) {
    let num = e.detail.value;
    num = parseInt(num, 10);
    if (isNaN(num)) {
      num = 1;
    }
    if (num <= 0) {
      num = 1;
    }
    this.setData({
      form: {
        number: num,
      },
    });
  },

  addCart(e) {
    this.submit('ADD_CART');
  },

  buyNow() {
    this.submit('BUY_NOW');
  },

  submit(type) {
    let _this = this;
    if (_this.data.form.number > _this.data.goods.num) {
      wx.showToast({
        title: '商品库存不足，请选择其它规格或数量',
        icon: 'none',
      });
      return true;
    }
    let attr_group_list = _this.data.attr_group_list;
    let checked_attr_list = [];
    for (let i in attr_group_list) {
      if (Object.prototype.hasOwnProperty.call(attr_group_list, i)) {
        let attr = false;
        for (let j in attr_group_list[i].attr_list) {
          if (attr_group_list[i].attr_list[j].checked) {
            attr = {
              attr_id: attr_group_list[i].attr_list[j].attr_id,
              attr_name: attr_group_list[i].attr_list[j].attr_name,
            };
            break;
          }
        }
        if (!attr) {
          wx.showToast({
            title: '请选择' + attr_group_list[i].attr_group_name,
            icon: 'none',
          });
          return true;
        } else {
          checked_attr_list.push({
            attr_group_id: attr_group_list[i].attr_group_id,
            attr_group_name: attr_group_list[i].attr_group_name,
            attr_id: attr.attr_id,
            attr_name: attr.attr_name,
          });
        }
      }
    }
    // 限购判断 by--lili
    let goods = _this.data.goods;
    if (goods.limit_count > 0) {
      let able_num =
        goods.limit_count -
        goods.user_order_count.cart -
        goods.user_order_count.order;
      if (_this.data.form.number > able_num) {
        wx.showToast({
          title: '当前最大购买数量为' + able_num,
          icon: 'none',
        });
        return;
      }
    }
    if (type === 'ADD_CART') {
      wx.showLoading({
        title: '正在提交',
        mask: true,
      });
      app.ws_micro_shoprequest({
        url: api.cart.add_cart,
        method: 'POST',
        data: {
          goods_id: _this.data.id,
          attr: JSON.stringify(checked_attr_list),
          num: _this.data.form.number,
        },
        success: function(res) {
          wx.showToast({
            title: res.msg,
            duration: 2000,
          });
          wx.hideLoading();
          _this.setData({
            show_attr_picker: false,
          });
          gatherAction &&
            gatherAction('addCart', 'success', { goodsID: _this.data.id });
        },
      });
    }
    if (type === 'BUY_NOW') {
      _this.setData({
        show_attr_picker: false,
      });
      wx.navigateTo({
        url:
          '/ws_micro_shop/pages/order-submit/order-submit?goods_info=' +
          JSON.stringify({
            goods_id: _this.data.id,
            attr: checked_attr_list,
            num: _this.data.form.number,
          }),
      });
    }
  },

  attrClick(e) {
    let _this = this;
    let attr_group_id = Number(e.currentTarget.dataset.groupId);
    let attr_id = Number(e.target.dataset.id);
    let attr_group_list = _this.data.attr_group_list;
    for (let i in attr_group_list) {
      if (Number(attr_group_list[i].attr_group_id) !== attr_group_id) {
        continue;
      }
      for (let j in attr_group_list[i].attr_list) {
        if (Number(attr_group_list[i].attr_list[j].attr_id) === attr_id) {
          attr_group_list[i].attr_list[j].checked = true;
        } else {
          attr_group_list[i].attr_list[j].checked = false;
        }
      }
    }
    _this.setData({
      attr_group_list,
    });
    let check_attr_list = [];
    let check_all = true;
    for (let i in attr_group_list) {
      if (Object.prototype.hasOwnProperty.call(attr_group_list, i)) {
        let group_checked = false;
        for (let j in attr_group_list[i].attr_list) {
          if (attr_group_list[i].attr_list[j].checked) {
            check_attr_list.push(attr_group_list[i].attr_list[j].attr_id);
            group_checked = true;
            break;
          }
        }
        if (!group_checked) {
          check_all = false;
          break;
        }
      }
    }
    if (!check_all) {
      return;
    }
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.default.goods_attr_info,
      data: {
        goods_id: _this.data.id,
        attr_list: JSON.stringify(check_attr_list),
      },
      success: function(res) {
        wx.hideLoading();
        if (res.code === 0) {
          _this.setData({
            'goods.attr_pic': res.data.pic,
            'goods.original_price': res.data.origin_price,
            'goods.oriprice': res.data.oriprice ? res.data.oriprice : 0,
            'goods.price': res.data.price,
            'goods.num': res.data.num,
            'goods.limit_count': res.data.limit_count,
            'goods.user_order_count': res.data.user_order_count,
          });
        }
      },
    });
  },

  gotoGoodsDetail(e) {
    gatherAction &&
      gatherAction('gotoGoodsDetail', 'success', {
        goodsID: e.currentTarget.dataset.goodsId,
      });
  },

  onSearchGoods() {
    let { keyword } = this.data;
    // keyword ||
    //   wx.showToast({
    //     title: '请输入关键词',
    //     icon: 'none',
    //   });
    this.setData({
      is_show_line: false,
    })
    this.reloadGoodsList(keyword);
  },

  onKeywordInput(e) {
    this.setData({ keyword: e.detail.value.trim() });
  },
});
